# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# AmosERP odoo11.0
# QQ:35350428
# 邮件:35350428@qq.com
# 手机：13584935775
# 作者：'odoo'
# 公司网址： www.odoo.pw  www.100china.cn www.amoserp.com
# Copyright 昆山一百计算机有限公司 2012-2020 Amos
# 日期：2019/11/14
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&


from odoo import api, fields, models, _
from odoo.exceptions import AccessError, UserError, ValidationError
from ding_client import Client
import datetime
from jinja2 import Template

class ding_users(models.Model):
    _name = 'ding.users'
    _description = u"钉钉会员"

    name = fields.Char(u'姓名')
    mobile = fields.Char(u'手机')
    email = fields.Char(u'邮件')

    ding_orderindepts = fields.Text(string=u'部门中排序', help=u'在对应的部门中的排序, Map结构的json字符串, key是部门的Id, value是人员在这个部门的排序值')
    ding_position = fields.Char(string=u'职位', help=u'长度为0~64个字符')
    ding_remark = fields.Char(string=u'备注', help=u'长度为0~1000个字符')
    ding_department = fields.Char(string=u'成员所属部门id列表', help=u'数组类型，数组里面值为整型，成员所属部门id列表')
    ding_unionid = fields.Char(string=u'用户ID')
    ding_tel = fields.Char(string=u'分机号', help=u'长度为0~50个字符')
    ding_userid = fields.Char(string=u'员工唯一标识')
    ding_orgemail = fields.Char(string=u'分配的邮件')
    ding_issenior = fields.Boolean(u"是否高管模式",
                                   help=u'true表示是，false表示不是。开启后，手机号码对所有员工隐藏。普通员工无法对其发DING、发起钉钉免费商务电话。高管之间不受影响')
    ding_workplace = fields.Char(string=u'办公地点', help=u'长度为0~50个字符')
    ding_isboss = fields.Boolean(u"是否老板", default=False)
    ding_jobnumber = fields.Char(string=u'员工工号', help=u'对应显示到OA后台和客户端个人资料的工号栏目。长度为0~64个字符')
    ding_ishide = fields.Boolean(string=u'是否号码隐藏',
                                 help=u'true表示隐藏, false表示不隐藏。隐藏手机号后，手机号在个人资料页隐藏，但仍可对其发DING、发起钉钉免费商务电话。')
    ding_extattr = fields.Char(string=u'扩展属性',
                               help=u'可以设置多种属性(但手机上最多只能显示10个扩展属性，具体显示哪些属性，请到OA管理后台->设置->通讯录信息设置和OA管理后台->设置->手机端显示信息设置)')
    ding_is_ding = fields.Boolean(u"是否开通钉钉", default=False)
    ding_isadmin = fields.Boolean(u"是否企业管理员", default=False)
    ding_openId = fields.Char(string=u'openId')
    ding_dingid = fields.Char(string=u'钉钉Id')
    ding_avatar = fields.Char(string=u'头像url')
    ding_tags = fields.Char(string=u'tags')
    ding_stateCode = fields.Char(string=u'stateCode')
    ding_isleaderindepts = fields.Char(string=u'在对应的部门中是否为主管')

    user_id = fields.Many2one('res.users', string=u'登陆帐号')


    ding_department_ids = fields.Many2many('hr.department', 'ding_users_departments_rel', 'user_id', 'department_id',
                                           string=u"所在部门")

    create_date = fields.Datetime(string=u'创建日期')
    ding_hiredate = fields.Date(u'入职时间', track_visibility='onchange', default=fields.Date.context_today)
    company_id = fields.Many2one('res.company', string=u'公司', default=lambda self: self.env.user.company_id)

    @api.onchange('ding_department_ids')
    def onchange_ding_department_ids(self):

        ding_department = []
        for department in self.ding_department_ids:
            ding_department.append(department.ding_id)

        self.ding_department = str(ding_department)

    def _check_ding_email(self):
        for phase in self:
            records = phase.search([('email', '=', self.email)])
            if len(records) > 1:
                return False
        return True

    _constraints = [
        (_check_ding_email, u'邮件必须唯一', ['email']),
    ]

    def _check_ding_mobile(self):
        for phase in self:
            records = phase.search([('mobile', '=', self.mobile)])
            if len(records) > 1:
                return False
        return True

    _constraints = [
        (_check_ding_mobile, u'手机必须唯一', ['mobile']),
    ]


    def action_bing_sync(self):
        for line in self:
            self._cr.execute("SELECT access_token FROM res_ding WHERE company_id = %s " % line.company_id.id)
            access_token = [r[0] for r in self._cr.fetchall()]

            if len(access_token) == 0:
                pass
                #:::执行生成token
            else:
                if len(line.email) == 0:
                    raise UserError(u'邮件不能为空!')
                if len(line.mobile) == 0:
                    raise UserError(u'手机不能为空!')




                client_obj = Client(None, None, access_token[0])
                params = {
                    "userid": line.ding_userid,
                    "name": line.name,
                    # "orderInDepts": line.ding_orderindepts or '{}',
                    "department": line.ding_department,
                    "position": line.ding_position or '',
                    "mobile": line.mobile or '',
                    "tel": line.ding_tel or '',
                    "workPlace": line.ding_workplace or '',
                    "remark": line.ding_remark or '',
                    "email": line.email or '',
                    "jobnumber": line.ding_jobnumber or '',
                    "ishide": line.ding_ishide or '',
                    "isSenior": line.ding_issenior or '',
                    "extattr": line.ding_extattr or {},
                }

                if line.ding_userid:
                    json = client_obj.user_update(params, access_token[0])
                    if json['errmsg'] == 'ok':
                        return True
                else:
                    json = client_obj.user_create(params, access_token[0])

                if json['errcode'] == 40014:
                    records = self.env['res.ding'].search([('company_id', '=', self.company_id.id)], limit=1)
                    records.action_gettoken()
                    self.action_bing_sync();
                else:
                    if json['errcode'] != 0:
                        raise ValidationError(json['errmsg'])
                parm = {
                    'ding_userid': json['userid'],
                }
                line.with_context(bing_sync=True).write(parm)
        return True

    def ding_messagers(self):
        """
        测试发送消息
        :return:
        """
        # self.env.user.d(self.env.user, "hi------Amos",None)



        records = self.env['ding.message.template'].sudo().search([('model', '=', 'hr.department'), ('code', '=', 'vic_001')], limit=1)
        if records:
            template = Template(records.body_html)
            content = template.render(docs=self)
            content = u'[等待审批] 申请人:%s\n向您!提交了一条%s等待审批信息,请即时审批!\n%s\n%s' % (self.env.user.name, 'Amos', content, '开发专家')
            self.env.user.d(self.env.user, content, None)
        else:
            pass
            # content = u'[等待审批] %s向您!提交了一条%s等待审批信息,单号为%s:,请即时审批！\n%s' % ( user.name, obj._description, obj.name, message)




        return True


class res_users(models.Model):
    _inherit = 'res.users'

    ding_id = fields.Many2one('ding.users', string=u'钉钉帐号')
    ding_userid = fields.Char(related='ding_id.ding_userid', store=True, string=u'钉钉唯一标识', readonly=True)
    is_ding_chat = fields.Boolean(u"是否接收钉钉提醒", default=True)

    def d(self, touser, message, param):
        """
        发送相关消息
        :param touser: 帐户
        :param message: 发送消息，尾部增加发送时间
        :param param: 提供额外的参数目前预留 格式为{'XX'：XX}
        :return:
        """
        if touser.is_ding_chat:  # 是否开始接收钉钉消息
            if touser.ding_userid == False:
                return True
                raise UserError(u'警告：当前用户帐号未关联钉钉帐号！')

            client_obj = Client(None, None, self.env.user.company_id.ding_id.access_token)
            n_days = datetime.datetime.now() + datetime.timedelta(hours=8)
            if not self.env.user.company_id.ding_id.agentid:
                raise UserError(u'警告：当前公司未关联到钉钉应用！')

            parm = {
                'agentid': self.env.user.company_id.ding_id.agentid,
                'msgtype': "text",
                'text': {
                    "content": message + '\n发送时间:' + n_days.strftime('%Y-%m-%d %H:%M:%S')
                },
            }
            if touser.ding_userid != None:
                parm['touser'] = touser.ding_userid

            json = client_obj.message_send(parm, self.env.user.company_id.ding_id.access_token)
            if json['errcode'] == 40014:
                self.env['res.ding'].sudo()._get_ding_access_token()
                self.env.user.d(touser.ding_userid, message, param)
            else:
                if json['errcode'] != 0:
                    raise ValidationError(json['errmsg'])

    def d_template(self, touser, message,model,template_id,param):
        """
        发送相关消息
        :param touser: 帐户
        :param message: 发送消息，尾部增加发送时间
        :param param: 提供额外的参数目前预留 格式为{'XX'：XX}
        :return:
        """


        records = self.env['ding.message.template'].sudo().search([('model', '=', model), ('code', '=', template_id)], limit=1)
        if records:
            template = Template(records.body_html)
            content = template.render(docs=self)
            content = u'[等待审批] 申请人:%s\n向您!提交了一条%s等待审批信息,请即时审批!\n%s\n%s' % (self.env.user.name, model._description, content, '0000')
            self.env.user.d(self.env.user, content, None)
        else:
            pass



class res_company(models.Model):
    _inherit = 'res.company'

    ding_id = fields.Many2one('res.ding', string=u'钉钉应用')
